package UDP;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPEchoClient {
    private String serverIP;
    private int serverPort;
    private DatagramSocket socket = null;

    public UDPEchoClient(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            if (!scanner.hasNext()) {
                break;
            }
            String request = scanner.next();

            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), 0, request.getBytes().length
            , InetAddress.getByName(serverIP), serverPort);

            socket.send(requestPacket);

            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);

            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient udpEchoClient = new UDPEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
